<?php

/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/5/29
 * Time: 18:25
 */

namespace app\common\service;


use app\api\model\Carts;
use app\api\model\Customer;
use app\api\model\Product;
use app\api\service\MailService;
use app\api\service\Order;
use League\MimeTypeDetection\EmptyExtensionToMimeTypeMap;
use think\Config;
use think\facade\Log;
use think\facade\Db;
use app\api\service\Order as OrderService;
use app\admin\model\Images;

class Mail
{
    // 发送邮件核心方法
    public static function send(string $template, $data = [])
    {
        try {
            // 根据模板ID选择数据源
            switch ($template) {
                case 'register':
                    return self::sendRegisterEmail($data);
                case 'cart':
                    return self::sendCartEmail();
                case 'code':
                    return self::sendCodeEmail($data);
                case 'order_partial_payment':
                    return self::sendOrderPartialPaymentEmail($data);
                case 'order_payment':
                    return self::sendOrderPaymentEmail($data);
                case 'order_shipped':
                    return self::sendOrderShippedEmail($data);
                case 'order_success':
                    return self::sendOrderSuccessEmail($data);
                case 'self_pickup':
                    return self::sendSelfPickupEmail($data);
                case 'coupon':
                    return self::sendCouponEmail($data);
                case 'order_refund':
                    return self::sendOrderRefundEmail($data);
                case 'order_cancel_timeout':
                    return self::sendOrderCancelTimeoutEmail($data);
                case 'order_cancel_price_change':
                    return self::sendOrderCancelPriceChangeEmail($data);
                default:
                    return [];
            }
        } catch (\Exception $e) {
            Log::error("Template data error: " . $e->getMessage());
            return false;
        }
    }
    #注册自动发邮件
    private static function sendRegisterEmail($data)
    {
        $params = [
            'to'  => $data,
            'subject'  => 'Jingle Mining - Thank you for signing up.',
            'template_id'  => 'register',
        ];
        $result =  MailService::sendEmailTemplate($params);
        return $result;
    }
    #注册自动发邮件
    private static function sendCodeEmail($data)
    {
        $params = [
            'to'  => $data['email'],
            'code'  => $data['code'],
            'subject'  => 'Jingle Mining - Your Verification Code ' . $data['code'],
            'template_id'  => 'code',
        ];

        $result =  MailService::sendEmailTemplate($params);
        return $result;
    }

    #创建优惠券发邮件
    private static function sendCouponEmail($data)
    {
        $str = $data['discount_type'] == 1 ? $data['discount_value'] . '%' : '$' . $data['discount_value'];
        $type = $data['discount_category'] == 1 ? " off products" : " off entire order";
        $discount_value = $str . $type;
        $params = [
            'to'  => '',
            'subject'  => "Jingle Mining - {$discount_value} Discount Coupon for you.",
            'template_id'  => 'coupon',
            'code_title'  => $data['code_title'],
            'user_name'  => '',
            'discount_value'  => $discount_value,

        ];
        if (empty($data['eligibility_value']) || $data['eligibility_type'] != 3) {
            return false;
        }
        # 用户信息
        $userInfo = Customer::whereIn('id', $data['eligibility_value'])->field('id,cusname,email')->select()->toArray();
        $userInfo = array_column($userInfo, null, 'id');
        foreach ($userInfo as $k => $v) {
            $params['to'] = $userInfo[$k]['email'];
            $params['user_name'] = $userInfo[$k]['cusname']; // todo 用户名不存在 取邮箱@之前
            MailService::sendEmailTemplate($params);
        }
    }
    #购物车存在商品未支付发邮件
    private static function sendCartEmail()
    {
        $params = [
            'to'  => '',
            'subject'  => 'Jingle Mining - You left an item in your cart！',
            'template_id'  => 'cart',
            'products'  => '',
            'user_name'  => '',
            'cart_url'  => config('domain.prod.mall') . '/cartOrder?type=cart&id=',

        ];
        /**
         * 1.查询所有购物车数据
         * 2.筛选满足发邮件的用户id
         * 3.调checkout 方法拿到数据
         */
        $cartData = Carts::select()->toArray();

        if (!$cartData) {
            return false;
        }
        $time = strtotime(date("Y-m-d H:00:00"));
        $time24 = $time - 86400;
        $time48 = $time - 172800;
        $userIds = [];
        foreach ($cartData as $cartDatum) {
            $cartTime = strtotime(date("Y-m-d H:00:00", strtotime($cartDatum['create_time'])));
            if ($cartTime == $time24 || $cartTime == $time48) {
                $userIds[] = $cartDatum['user_id'];
            }
        }
        $userIds = array_unique($userIds);
        if (empty($userIds)) {
            return false;
        }
        # 用户信息
        $userInfo = Customer::whereIn('id', $userIds)->field('id,cusname,email')->select()->toArray();
        $userInfo = array_column($userInfo, null, 'id');
        $cartIds = [];
        foreach ($cartData as $cart) {
            if (in_array($cart['user_id'], $userIds)) {
                $cartIds[$cart['user_id']][] = $cart['id'];
            }
        }
        $orderService = new Order();
        foreach ($userIds as $uid) {
            $params['to'] = $userInfo[$uid]['email'];
            $params['user_name'] = $userInfo[$uid]['cusname']; // todo 用户名不存在 取邮箱@之前
            $params['cart_url'] = $params['cart_url'] . implode(',', $cartIds[$uid]);
            $cartParam = [
                'method'    => 'cart',
                'product'   => $cartIds[$uid],
                'user_id'   => $uid,
                'lang'      => 'en',

            ];
            $cartInfo = $orderService->checkout($cartParam);
            $pInfo = '';
            $product = new Product();
            foreach ($cartInfo['data']['product'] as $p) {
                $unit = $product->getUnitAttr('', $p);
                $arrival_date = $p['arrival_date'] ? $p['arrival_date'] : 'In Stock';
                $hashrate = $p['hashrate'] . $unit;
                $pInfo .= '<div class="product-section">
                <img src="' . $p['main_photo'] . '"  class="product-img"><div class="product-details">
                <h3 class="product-name">' . $p['cname'] . '</h3>
                <p class="product-hashrate">' . $hashrate . '</p>
                <p class="product-stock">✔ ' . $arrival_date . '</p>
                <p class="product-price">$' . $p['sales_price'] . '</p> </div></div>';
            }
            $params['products'] = $pInfo;
            MailService::sendEmailTemplate($params);
        }
        return true;
    }


    private static function sendOrderPaymentEmail($data)
    {
        $userInfo = Db::name('customer')->where('id', $data['user_id'])->find();
        $subject = 'Jingle Mining  Order No.' . $data['order_no'] . ' confirmed';
        $detailParams = [
            'user_id' => $data['user_id'],
            'orderNo' => $data['order_no'],
            'lang' => 'en',
        ];
        $orderService = new OrderService();
        $orderInfo = $orderService->detail($detailParams)['data'];
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_payment',
            'order_info' => $orderInfo,
            'user_info' => $userInfo,
        ];
        MailService::sendEmailTemplate($params);
    }
    /**
     * @describe 订单部分支付邮件
     * @author: Bobo
     * @date: 2025-05-30 14:00:10
     * @param [type] @required
     * @return Renderable
     */
    private static function sendOrderPartialPaymentEmail($data)
    {
        $userInfo = Db::name('customer')->where('id', $data['user_id'])->find();

        $detailParams = [
            'user_id' => $data['user_id'],
            'orderNo' => $data['order_no'],
            'lang' => 'en',
        ];
        $orderService = new OrderService();
        $orderInfo = $orderService->detail($detailParams)['data'];

        $subject = 'Jingle Mining - INVOICE Order No.' . $orderInfo['order_no'] . ' Please complete your Order';
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_partial_payment',
            'order_info' => $orderInfo,
            'user_info' => $userInfo,
        ];
        MailService::sendEmailTemplate($params);
    }

    private static function sendOrderShippedEmail($data)
    {
        // 这里传进来的是物流单信息 和 订单信息 
        $logistics = $data['logistics'];
        $logistics['company_name'] = Db::name('logistics_company')->where('id', $logistics['company_id'])->value('name');
        $orderInfo = $data['order_info'];
        $userInfo = Db::name('customer')->where('id', $orderInfo['user_id'])->find();

        $logistics_product_items = Db::name('logistics_order_item')
            ->alias('a')
            ->join('db_product b', 'a.product_id = b.id')
            ->where('a.logistics_order_id', $logistics['id'])
            ->where('a.order_id', $orderInfo['id'])
            ->field('a.product_id,a.number as quantity,b.cname as name,b.main_photo')
            ->select()
            ->toArray();
        $imagesIds = array_column($logistics_product_items, 'main_photo');
        $imagesModel = new Images();
        $imagesList = $imagesModel->getImagesByIds($imagesIds);
        $imagesList = array_column($imagesList, null, 'id');
        $logistics_product_items = array_map(function ($item) use ($imagesList) {
            $item['thumb'] = $imagesList[$item['main_photo']]['url'];
            return $item;
        }, $logistics_product_items);





        $subject = 'Jingle Mining -  A shipment from Order No.' . $orderInfo['order_no'] . 'is on the way';
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_shipped',
            'order_info' => $orderInfo,
            'user_name' => $userInfo['cusname'],
            'logistics_product_items' => $logistics_product_items,
            'logistics' => $logistics,
        ];
        MailService::sendEmailTemplate($params);
    }

    /**
     * @describe 订单创建成功
     * @author: xu
     * @date: 2025-05-30 15:00:10
     * @param [type] @required
     * @return Renderable
     */
    private static function sendOrderSuccessEmail($data)
    {
        $userInfo = Db::name('customer')->where('id', $data['user_id'])->find();
        $detailParams = [
            'user_id' => $data['user_id'],
            'orderNo' => $data['order_no'],
            'lang' => 'en',
        ];
        $orderService = new OrderService();
        $orderInfo = $orderService->detail($detailParams)['data'];
        $subject = 'Jingle Mining - INVOICE Order No.' . $orderInfo['order_no'];
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_success',
            'order_info' => $orderInfo,
            'user_info' => $userInfo,
        ];
        MailService::sendEmailTemplate($params);
    }

    /**
     * @describe 自提订单发送邮件
     * @author: xu
     * @date: 2025-05-30 15:00:10
     * @param [type] @required
     * @return Renderable
     */
    private static function sendSelfPickupEmail($data)
    {
        $userInfo = Db::name('customer')->where('id', $data['user_id'])->find();
        $detailParams = [
            'user_id' => $data['user_id'],
            'orderNo' => $data['order_no'],
            'lang' => 'en',
        ];
        $orderService = new OrderService();
        $orderInfo = $orderService->detail($detailParams)['data'];

        $products = implode(',', array_column($orderInfo['list'], 'name'));
        $pickup_address = array_unique(array_column($orderInfo['list'], 'pickup_address'));
        $pickup = '';
        foreach ($pickup_address as $p) {
            $pickup .= "<p>$p</p>";
        }
        $subject = 'Jingle Mining - The Self-Pickup Appointment Voucher File of ' . $products . ' in Your Order No.' . $orderInfo['order_no'];
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'self_pickup',
            'order_info' => $orderInfo,
            'user_info' => $userInfo,
            'products' => $products,
            'pickup_address' => $pickup
        ];
        MailService::sendEmailTemplate($params);
    }

    private static function sendOrderRefundEmail($data)
    {
        // 这里传进来的是订单编号

        $orderService = new OrderService();
        $orderInfo = $orderService->detail($data['orderInfo'])['data'];


        $userInfo = Db::name('customer')->where('id', $orderInfo['user_id'])->find();

        $subject = 'Jingle Mining - Order No.' . $orderInfo['order_no'] . 'Refund notification';
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_refund',
            'user_name' => $userInfo['cusname'],
            'order_info' => $orderInfo,
            'returnorder_paid_amount' => $data['returnorderInfo']['returnorder_paid_amount'],

        ];
        MailService::sendEmailTemplate($params);
    }

    private static function sendOrderCancelTimeoutEmail($data)
    {
        $userInfo = Db::name('customer')->where('id', $data['user_id'])->find();
        $subject = 'Jingle Mining - Order No.' . $data['order_no'] . ' Cancel notification';
        $detailParams = [
            'user_id' => $data['user_id'],
            'orderNo' => $data['order_no'],
            'lang' => 'en',
        ];
        $orderService = new OrderService();
        $orderInfo = $orderService->detail($detailParams)['data'];
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_cancel_timeout',
            'user_name' => $userInfo['cusname'],
            'order_info' => $orderInfo,
        ];
        MailService::sendEmailTemplate($params);
    }

    private static function sendOrderCancelPriceChangeEmail($data)
    {
        $userInfo = Db::name('customer')->where('id', $data['user_id'])->find();
        $subject = 'Jingle Mining - Order No.' . $data['order_no'] . ' Cancel notification';
        $detailParams = [
            'user_id' => $data['user_id'],
            'orderNo' => $data['order_no'],
            'lang' => 'en',
        ];
        $orderService = new OrderService();
        $orderInfo = $orderService->detail($detailParams)['data'];
        $params = [
            'to'  => $userInfo['email'],
            'subject'  => $subject,
            'template_id'  => 'order_cancel_price_change',
            'user_name' => $userInfo['cusname'],
            'order_info' => $orderInfo,
        ];
        MailService::sendEmailTemplate($params);
    }
}
